package com.doitedu.doit30.hbase.utils;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;

import java.io.IOException;

/**
 * @Date 22.6.9
 * @Created by HANGGE
 * @Description hbase工具类
 */
public class HbaseUtil {


    /**
     * 解析hbase中的行数据
     *
     * @param result
     */
    public static void showData(Result result) {
        while (result.advance()) {
            Cell cell = result.current();
            byte[] cfB = CellUtil.cloneFamily(cell);
            byte[] rowB = CellUtil.cloneRow(cell);
            byte[] qualifier = CellUtil.cloneQualifier(cell);
            byte[] value = CellUtil.cloneValue(cell);
            String qualifierStr = new String(qualifier);
            if (!"temperament".equals(qualifierStr)) {
                System.out.println("行键: " + new String(rowB)
                        + "   列族: " + new String(cfB)
                        + "   属性: " + new String(qualifier)
                        + "   值: " + new String(value)
                );
            } else {
                // 打印结果
                System.out.println("行键: " + new String(rowB)
                        + "   列族: " + new String(cfB)
                        + "   属性: " + new String(qualifier)
                        // 根据写入的数据类型获取值
                        + "   值: " + Bytes.toDouble(value)
                );
            }

        }
    }

    /**
     * 获取  Hbase连接对象
     *
     * @return
     * @throws Exception
     */
    public static Connection getHbaseConnection() throws Exception {
        Configuration conf = HBaseConfiguration.create();
        // conf.set("hbase.client.write.buffer" , "");
        // 设置zookeeper的地址   通过ZK可以连接到hbase数据库
        conf.set("hbase.zookeeper.quorum", "linux01:2181,linux02:2181,linux03:2181");
        // 2 连接hbase数据库
        Connection conn = ConnectionFactory.createConnection(conf);
        return conn;
    }

    /**
     * 返回 Admin  管理对象
     *
     * @param conn 连接对象
     * @return
     * @throws Exception
     */
    public static Admin getAdmin(Connection conn) throws Exception {
        return conn.getAdmin();

    }

    /**
     * 根据表名获取表对象
     *
     * @param conn
     * @param tableName
     * @return
     * @throws IOException
     */
    public static Table getTable(Connection conn, String tableName) throws Exception {
        return conn.getTable(TableName.valueOf(tableName));
    }


}
